# coding: UTF-8

import io
import sys
import os
import re
import shutil

from YTSTools import file
from YTSTools import convert

class Blog(object):
    def __init__(self, userArgs, config, project):
        self.userArgs = userArgs
        self.project = project
        self.config = config

        self.program_address = userArgs.get('program_address')
        self.ignores = project.get('ignores', [])
        self.ignores.extend(config.get('ignores', []))
        self.source = os.path.abspath(project.get('source', ''))
        self.target = os.path.abspath(project.get('target', ''))
        self.template = os.path.abspath(project.get('template', "./templates/default"))

    def __print_init_args__(self):
        print('program_address:', self.program_address)
        print('source:', self.source)
        print('target:', self.target)
        print('template:', self.template)

    def Generate(self):
        target_posts = os.path.join(self.target, '_posts')
        self.copyfiles(self.source, target_posts,
            ignores=self.ignores,
            resolveInterface=self.source_resolve_interface)

        data_path = os.path.join(self.target, 'data.json')
        file.config_json_file_write(data_path, self.project.get('info', {}))

        self.copyfiles(self.template, self.target,
            ignores=[ '_posts$', ],
            resolveInterface=self.template_resolve_interface)

    def copyfiles(self, sourceRoot, targetRoot, ignores, resolveInterface):
        paths = file.get_all_file_paths(sourceRoot, ignores=ignores)
        for path in paths:
            newpath = path.replace(sourceRoot, targetRoot)
            (newpathdir, newpathfile) = os.path.split(newpath)
            if not os.path.exists(newpathdir):
                os.makedirs(newpathdir)
            extension_name = os.path.splitext(newpathfile)[1]
            IResolve = resolveInterface(extension_name, {
                'sourceFilePath': path,
                'targetFilePath': newpath,
            })
            isResolveSuccess = self.resolve_file(IResolve)
            if not isResolveSuccess:
                shutil.copy(path, newpath)
                print("复制文件:", newpath)

    def resolve_file(self, IResolve):
        if IResolve is None:
            return False
        isResolveSuccess = False
        if IResolve.IsReWrite():
            rpath = IResolve.ReWriteFilePath()
            rContent = IResolve.ReWriteContent()
            if rpath and rContent:
                file.file_write(rpath, rContent)
                print("生成文件:", rpath)
                isResolveSuccess = True
        fileType = IResolve.FileType() + 's'
        info = self.project.get('info', {})
        fileTypeVs = info.get(fileType, [])
        fileTypeVs.append(IResolve.Data())
        info[fileType] = fileTypeVs
        self.project['info'] = info
        return isResolveSuccess

    def source_resolve_interface(self, extension_name, info):
        if extension_name in ['.md', '.markdown']:
            from Resolve_Source_Markdown import Resolve_Source_Markdown
            return Resolve_Source_Markdown(self, info)
        return None

    def template_resolve_interface(self, extension_name, info):
        if extension_name == '.html' or extension_name == '.htm':
            from Resolve_Template_Html import Resolve_Template_Html
            return Resolve_Template_Html(self, info)
        return None
